<template>
  <div class="container">
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="searchForm" class="search-form" label-position="left">
      <el-form-item label="ID">
        <el-input v-model.number="searchForm.id"/>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="searchForm.name"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="default" @click="resetSearchForm">重置</el-button>
        <el-button type="primary" @click="showAddDialog">添加</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%">
      <!-- ID列 -->
      <el-table-column prop="id" label="ID"></el-table-column>
      <!-- 名称列 -->
      <el-table-column prop="name" label="名称" width="100"></el-table-column>
      <!-- 地址列 -->
      <el-table-column prop="address" label="地址" width="200"></el-table-column>
      <!-- 经度列 -->
      <el-table-column prop="longitude" label="经度"></el-table-column>
      <!-- 纬度列 -->
      <el-table-column prop="latitude" label="纬度"></el-table-column>
      <!-- 图片列 -->
      <el-table-column prop="image" label="图片">
        <template #default="{row}">
          <img :src="row.image" style="max-width:100%;max-height:100%;">
        </template>
      </el-table-column>
      <!-- 公告列 -->
      <el-table-column prop="notice" label="公告"></el-table-column>
      <!-- 电话列 -->
      <el-table-column prop="phone" label="电话" width="150"></el-table-column>
      <!-- 最低价格列 -->
      <el-table-column prop="minPrice" label="最低价格"></el-table-column>
      <!-- 配送费列 -->
      <el-table-column prop="deliveryFee" label="配送费"></el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" width="140">
        <template #default="{row}">
          <el-button type="primary" size="small" @click="editItem(row.id)">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteItem(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑" :before-close="handleClose">
      <el-form :model="currentItem" label-position="left" label-width="80px">
        <el-form-item label="ID" v-if="isEdit">
          <el-input v-model="currentItem.id" disabled/>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="currentItem.name"/>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="currentItem.address"/>
        </el-form-item>
        <el-form-item label="经度">
          <el-input v-model="currentItem.longitude"/>
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="currentItem.latitude"/>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              action="http://127.0.0.1:8080/api/upload/image"
              :headers="{Authorization:getToken}"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
              list-type="picture"
              :before-upload="beforeUpload"
          >
            <el-button type="primary">点击上传图片</el-button>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 20MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="公告">
          <el-input v-model="currentItem.notice"/>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="currentItem.phone"/>
        </el-form-item>
        <el-form-item label="最低价格">
          <el-input v-model.number="currentItem.minPrice"></el-input>
        </el-form-item>
        <el-form-item label="配送费">
          <el-input v-model.number="currentItem.deliveryFee"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveItem">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {
  createRestaurant,
  deleteRestaurant,
  getRestaurantDetail,
  getRestaurantList,
  updateRestaurant
} from "@/api/restaurant";
import {ElMessage} from "element-plus";
import {getUserToken} from "@/utils/userIsLogin";

export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      // 对话框可见性
      dialogVisible: false,
      // 当前编辑项
      currentItem: {},
      // 是否为编辑模式
      isEdit: false,
      // 搜索表单
      searchForm: {
        id: null,
        name: ''
      },
      fileList: []
    }
  },
  created() {
    // 初始化表格数据
    this.fetchTableData()
  },
  computed:{
    getToken(){
      return `Bearer ${getUserToken()}`
    }
  },
  methods: {
    // 获取表格数据
    fetchTableData() {
      this.isEdit = false
      getRestaurantList().then(({data}) => {
        this.tableData = data
      }).catch(err => {
        ElMessage.error('获取餐厅列表失败')
        console.log(err)
      })
    },
    // 编辑项
    editItem(id) {
      getRestaurantDetail(id).then(({data}) => {
        this.currentItem = data
        // 打开编辑对话框
        this.dialogVisible = true
        // 设置为编辑模式
        this.isEdit = true
      }).catch(err => {
        ElMessage.error('获取餐厅详情失败')
        console.log(err)
      })
    },
    // 删除项
    deleteItem(id) {
      // 弹出
      this.$confirm('确定删除该项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 在这里执行删除操作，可以向后台发起请求，也可以直接在前端删除
          await deleteRestaurant(id)
          // 弹出删除成功提示
          this.$message({
            type: 'success',
            message: '删除成功！'
          })
          this.fetchTableData()
        } catch (e) {
          ElMessage.error('删除餐厅失败')
          console.log(e)
        }
      }).catch(() => {
        // 取消删除，不需要执行任何操作
      })
    },
    // 保存项
    saveItem() {
      if (this.isEdit) {
        updateRestaurant(this.currentItem.id, this.currentItem).then(res => {
          this.fetchTableData();
          ElMessage.success('更新餐厅成功')
        }).catch(err => {
          ElMessage.error('更新餐厅失败')
          console.log(err)
        });
      } else {
        createRestaurant(this.currentItem).then(res => {
          this.fetchTableData();
          ElMessage.success('添加餐厅成功')
        }).catch(err => {
          ElMessage.error('添加餐厅失败')
          console.log(err)
        });
      }
      // 关闭对话框
      this.dialogVisible = false
      // 清空当前编辑项
      this.currentItem = {}
      // 取消编辑模式
      this.isEdit = false
    },
    // 打开添加对话框
    showAddDialog() {
      this.currentItem = {}
      this.dialogVisible = true
    },
    // 搜索
    handleSearch() {
      // 模拟搜索操作，可以向后台发起请求，也可以直接在前端过滤数据
      this.tableData = this.tableData.filter(val => {
        let result = true
        if (this.searchForm.id !== null) {
          result = result && val.id === this.searchForm.id
        }
        if (this.searchForm.name !== '') {
          result = result && val.name.includes(this.searchForm.name)
        }
        return result
      })
    },
    // 重置搜索表单
    resetSearchForm() {
      this.searchForm = {
        id: null,
        name: ''
      }
      // 重新获取表格数据
      this.fetchTableData()
    },
    // 关闭对话框前执行的操作
    handleClose(done) {
      if (this.dialogVisible) {
        this.$confirm('确定关闭对话框吗？未保存的修改将会丢失！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          done()
        }).catch(() => {
          // 取消关闭对话框
        })
      } else {
        done()
      }
    },
    // 处理上传成功地回调
    handleUploadSuccess(response) {
      // 如果上传成功，将文件路径保存到 currentIte。image
      if (response.msg === '请求成功') {
        this.currentItem.image = response.data.uploadUrl;
        console.log('上传成功！文件路径为：', response.data.uploadUrl);
      } else {
        // 上传失败，弹出提示
        ElMessage.error('上传失败，请重试！');
      }
    },
    // 在上传之前的操作
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        ElMessage.error('上传文件只能是 JPG 或 PNG 格式！');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        ElMessage.error('上传文件大小不能超过 20MB！');
        return false;
      }
      return true;
    },
    handlePreview(file) {
      console.log(file,'<<<----handlePreview');
    },
    handleRemove(uploadFile, uploadFiles) {
      console.log(uploadFile, uploadFiles,'<<<----handleRemove');
    }
  }
}
</script>

<style scoped>
.search-form {
  margin-bottom: 10px;
}
</style>
